const Koa = require("koa"),
  route = require("koa-route"),
  websockify = require("koa-websocket");

const app = websockify(new Koa());
// Regular middleware
// Note it's app.ws.use and not app.use
app.ws.use(function (ctx, next) {

  ctx.websocket.on("message", (data) => {
    const result = JSON.parse(data);
    if (result.type === "updateChatHistory") {
      // 通知所有客户端获取最新的聊天
      // ctx.websocket.send(JSON.stringify({ type: "getChatHistory" }));
      app.ws.server.clients.forEach((client, i) => {
        client.send(JSON.stringify({ type: "getChatHistory" }));
      })
    }
  });
  
  return next(ctx);
});

app.listen(7000);
